//
//  BKMyOrderDetailController.m
//  bestkeep
//
//  Created by Mr. Wu on 16/12/12.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKMyOrderDetailController.h"
#import "BKMyOrderGetDataFromNetWork.h"
#import "BKMyOrderDetailCell.h"
#import "BKMyOrderDerTableviewCellHederAndFooter.h"
#import "Mediator+BKGD.h"
#import "BK_my_EvaluationOfDryingVC.h"
#import "BKMyOrderAlert.h"
#import "Mediator+BKOrder.h"
#import "BK_My_DetailOrder_CellModel.h"
#import "BKMyOrderChooseGoEvaluatingVC.h"
#import "BKMyOrderCheckLogisticsController.h"
#import "BKMyOrderRetuanGoodDetailController.h"
#import "BKMyOrderSplitController.h"
#import "BK_ODetail_Tool.h"
#define ReceiveGoodS 100//aletView的tag
#define DeleteOrder 200
@interface BKMyOrderDetailController ()<UITableViewDelegate,UITableViewDataSource,BKOrderFooterViewDelegate,UIAlertViewDelegate,CancelOrderDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,strong)BK_My_DetailOrder_Model *model_BKMy_Order;
@property(nonatomic,strong)NSString *Order_id;//订单id,确认收货用;


@property(nonatomic,strong) ExceptionView *exceptionView;

@end
@implementation BKMyOrderDetailController

-(NSMutableArray *)sectionArray{
    if (!_sectionArray) {
        _sectionArray = [NSMutableArray array];
    }return _sectionArray;
}

-(void)viewDidLoad{
    self.title  = @"订单详情";
    self.view.backgroundColor = [UIColor whiteColor];
        [self initview];
    [self getDataFormNetWork];
    self.edgesForExtendedLayout = UIRectEdgeNone;
}
-(void)initview{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,self.view.bounds.size.height-64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource  = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = ThemeBackgroundColor;
    [self.view addSubview:self.tableView];
    
}
-(void)getDataFormNetWork{
    if (self.exceptionView) {
        [self.exceptionView dismiss];
        self.exceptionView = nil;
    }
    [BKIndicationView showInView:self.view];
    [BKMyOrderGetDataFromNetWork GetOrderDetail:self.Order_no Success:^(NSArray *sectionModel) {
    
        [BKIndicationView dismiss];
    
        [self.sectionArray removeAllObjects];
    
        [self.sectionArray addObjectsFromArray:sectionModel];
    
        BK_My_DetailOrder_SectionModel *section = self.sectionArray[0];
        
        /*
         * 获取BKMy_OrderModel
         */
        self.model_BKMy_Order = section.Ordermodel;
        
        if (self.ordermodel) {
            
            //如果上一级页面传递了退换货的参数
            
        }else{
            //如果没有自己解析
            
            [self create_BKMyOrderModel_For_TuiHuanHuo:self.model_BKMy_Order];
            
        }
        
        
        self.Order_id = self.model_BKMy_Order.order_id;
        
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [BKIndicationView dismiss];
      
        
        
        
        ExceptionCodeType errorType;
        if (error.code == -1009) {
            errorType = ExceptionCodeTypeNoNetwork;
        }else if (error.code == -1001){
            errorType = ExceptionCodeTypeRequestFailed;
        }else if (error.code == 502 || error.code == 404){
            errorType = ExceptionCodeTypeServerError;
        }else{
            errorType = ExceptionCodeTypeFailedToLoad;
        }
        
        self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
        ExceptionViewAction *action = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
            [self.exceptionView dismiss];
            self.exceptionView = nil;
            [self getDataFormNetWork];
        }];
        
        [self.exceptionView addAction:action];
        [self.exceptionView showInView:self.view];

    }];
}

/*
 * 构建数据给退换货使用
 */
-(void)create_BKMyOrderModel_For_TuiHuanHuo:(BK_My_DetailOrder_Model *)model{
    
    BK_My_Order_rows_Model * model_BKMyOrder=[[BK_My_Order_rows_Model alloc]init];
    //订单号
    model_BKMyOrder.order_no=model.order_no;
    //用户下单时间
    model_BKMyOrder.order_created_date = model.order_create_time;
    //发货地
    model_BKMyOrder.deliver = model.ship_address;
    
    NSMutableArray * marr_item_list=[[NSMutableArray alloc]init];
    
    for (BK_My_DetailOrder_OrderList_Model * orderlist_model in model.order_list) {
        
        BK_My_Order_rows_itemList_Model * model_OrderDetail=[[BK_My_Order_rows_itemList_Model alloc]init];
        
        model_OrderDetail.order_item_id =orderlist_model.itemId;       //  订单子项表ID
        model_OrderDetail.goods_id =orderlist_model.goods_id;//商品id
        model_OrderDetail.goods_img =orderlist_model.goods_img;  //商品图片
        model_OrderDetail.goods_name =orderlist_model.goods_name;  //商品名
        model_OrderDetail.sale_property =orderlist_model.sale_property;  //商品属性参数
        model_OrderDetail.member_price =orderlist_model.goods_price;  //会员价
        model_OrderDetail.amount =orderlist_model.goods_amount;   //商品数量"
        model_OrderDetail.plan_deliver_date =orderlist_model.plan_deliver_date;//预计发货日期
        model_OrderDetail.evaluation_flag =orderlist_model.evaluationFlag;//评价标识 1去评价,0不评价"
        model_OrderDetail.returnFlag =orderlist_model.returnFlag;//退换货;returnFlag
        
        [marr_item_list addObject:model_OrderDetail];
        
    }
    
    model_BKMyOrder.item_list=marr_item_list;
    
    self.ordermodel=model_BKMyOrder;

    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sectionArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[section];
    return sectionModel.cells.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[indexPath.section];
    BK_My_DetailOrder_CellModel *cellModel = (BK_My_DetailOrder_CellModel*)sectionModel.cells[indexPath.row];
    BKMyOrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellModel.reuseIdentifier];
    if (!cell) {
        
        cell = [[NSClassFromString(cellModel.className) alloc]initWithStyle:UITableViewCellStyleDefault     reuseIdentifier:cellModel.reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    return cell;
    
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BK_My_DetailOrder_SectionModel *sec = self.sectionArray[indexPath.section];
    BK_My_DetailOrder_CellModel *row = (BK_My_DetailOrder_CellModel *)sec.cells[indexPath.row];
    NSString *str = NSStringFromClass([BK_OD_Goods class]);
    if ([row.className isEqualToString:str]) {
        UIViewController *vc = [[Mediator sharedInstance]BKGD_goodsDetailViewController:row.OrderlistModel.goods_id saleTypes:nil];
        [self.navigationController pushViewController:vc animated:YES];
    
    }
   }
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    BK_My_DetailOrder_SectionModel * sect = self.sectionArray[indexPath.section];
    BK_My_DetailOrder_CellModel *cellModel = (BK_My_DetailOrder_CellModel*)sect.cells[indexPath.row];
    
    
    if ([cell respondsToSelector:@selector(fillData:)]) {
        
        [cell performSelector:@selector(fillData:) withObject:cellModel];
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[section];
    BKMyOrderDerTableviewCellHederAndFooter *header = (BKMyOrderDerTableviewCellHederAndFooter*) [tableView dequeueReusableHeaderFooterViewWithIdentifier:sectionModel.reuseIdentifier];
    if (!header) {
        header = [[NSClassFromString(sectionModel.HeadeViewClassName) alloc]init];
        header.sectiondelegate = self;
        if ([header respondsToSelector:@selector(fillData:)]) {
            
            [header performSelector:@selector(fillData:) withObject:sectionModel];
        }
        
    }
    return header;
    
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[section];
    BKMyOrderDerTableviewCellHederAndFooter *Footer = (BKMyOrderDerTableviewCellHederAndFooter*) [tableView dequeueReusableHeaderFooterViewWithIdentifier:sectionModel.reuseIdentifier];
    if (!Footer) {
        Footer = [[NSClassFromString(sectionModel.FootViewClassName) alloc]init];
        Footer.sectiondelegate = self;
        if ([Footer respondsToSelector:@selector(fillData:)]) {
            
            [Footer performSelector:@selector(fillData:) withObject:sectionModel];
        }
        
    }
    return Footer;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[indexPath.section];
    BK_My_DetailOrder_CellModel *cellModel = (BK_My_DetailOrder_CellModel*)sectionModel.cells[indexPath.row];
    return cellModel.height;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[section];
    if (sectionModel.headerhHeight) {
        return sectionModel.headerhHeight;
        
    }
    return 0.1;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    BK_My_DetailOrder_SectionModel *sectionModel = self.sectionArray[section];
    if (sectionModel.footerHeight) {
        return sectionModel.footerHeight;
    }
    return 0.1;
    
}
//明细按钮;
- (void)BKOrderFooterViewDelegate_ShowBtn:(CGFloat )height{
        BK_My_DetailOrder_SectionModel *section = self.sectionArray[4];//有预计发货时间
    if (self.sectionArray.count == 5) {
       section = self.sectionArray[3];//没有预计发货时间
    }
    section.footerHeight = height;
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}

//点击按钮组
- (void)BKOrderFooterViewDelegate_ClickBtn:(UIButton *)btn{
    NSString *str = btn.titleLabel.text;
    
    if ([str isEqualToString:@"删除订单"]) {
        [self gotoDeleteOrder];
    }
    if ([str isEqualToString:@"确认收货"]) {
        [self gotoConfrimReciveGoods];
    }
    if ([str isEqualToString:@"去评价"]) {
        [self gotoEvaluation];
    }
    if ([str isEqualToString:@"取消订单"]) {
        [self gotoCanCelorder];
    }
    if ([str isEqualToString:@"去付款"]) {
        [self gotoPayVC];
    }
    
    if ([str isEqualToString:@"查看物流"]) {
        [self gotoLogistics];
    }
    if ([str isEqualToString:@"退换货"]) {
        [self gotoReturngoods];
    }
    if ([str isEqualToString:@"拆单"]) {
             [self gotoSplitOrder];
        }

    
}
#pragma mark: 删除订单;
-(void)gotoDeleteOrder{
    UIAlertView *alertVA = [[UIAlertView alloc]initWithTitle:@"确认删除订单？" message:@"\n删除之后可以从电脑端订单回收站恢复" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertVA.tag=DeleteOrder;
    [alertVA show];
    
}
-(void)gotoConfrimReciveGoods{
    UIAlertView *alertVA = [[UIAlertView alloc]initWithTitle:@"\n确认收货？\n"  message:nil  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alertVA.tag=ReceiveGoodS;
    [alertVA show];
    
}
#pragma mark========================delegate【确认收货】【删除订单】====================
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //确认收货;
    if (alertView.tag == ReceiveGoodS) {
        NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
        if ([btnTitle isEqualToString:@"取消"]) {
        }else if ([btnTitle isEqualToString:@"确定"] ) {
            [BKMyOrderGetDataFromNetWork ConfrimReceiveGoodsWithOrderID:self.Order_id Status:^(NSString *str) {
                if ([str isEqualToString:@"1"]) {
                    [HUD showSuccessMessage:@"确认收货成功"];
                       [self.navigationController popViewControllerAnimated:YES];
                                   }
            } ];
        }
        //删除订单;
    }else if(alertView.tag == DeleteOrder){
        NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
        if ([btnTitle isEqualToString:@"取消"]) {
        }else if ([btnTitle isEqualToString:@"确定"] ) {
            [BKMyOrderGetDataFromNetWork DeleteOrderdataWithOrderID:self.Order_id Status:^(NSString *str) {
                if ([str isEqualToString:@"1"]) {
                    [HUD showSuccessMessage:@"删除订单成功"];
                    if (_reloadData)
                    {
                        _reloadData(@"YES");
                    }

                    [self.navigationController popViewControllerAnimated:YES];
                 
                }
                else{
                    [HUD showMessage:str];
                }
            }];
        }
    }
}
#pragma mark ------去评价;
-(void)gotoEvaluation{
    if (self.model_BKMy_Order.order_list.count>1) {
        BKMyOrderChooseGoEvaluatingVC *vc = [[BKMyOrderChooseGoEvaluatingVC alloc]init];
        vc.ordId = self.Order_id;
      [self.navigationController pushViewController:vc animated:YES];
    }
    else{
        BK_my_EvaluationOfDryingVC *vc = [[BK_my_EvaluationOfDryingVC alloc] init];
        BK_My_DetailOrder_OrderList_Model *listModel = self.model_BKMy_Order.order_list[0];
        vc.goodsId = listModel.goods_id;
        vc.order_id = self.Order_id;
        vc.order_item_id = listModel.itemId;
        vc.img  = listModel.goods_img;
        vc.name = listModel.goods_name;
        vc.reloadData = ^(NSString *remove){
                [self  getDataFormNetWork];
            if (_reloadData)
            {
            _reloadData(@"YES");
            }
            };
        [self.navigationController pushViewController:vc animated:YES];
    }
   
}
#pragma mark ---取消订单
-(void)gotoCanCelorder{
    
    BKMyOrderAlert *alertView= [BKMyOrderAlert makeViewWithMask:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    alertView.delegate = self;
    
}
-(void)cancelOrderbuttonClick:(NSString *)str{
    [BKMyOrderGetDataFromNetWork CancelOrder:self.Order_id reason:str Status:^(NSString *str) {
        if ([str isEqualToString:@"1"]) {
            [HUD showSuccessMessage:@"取消订单成功"];
            if (_reloadData)
            {
                _reloadData(@"YES");
            }
             [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

#pragma mark -----去付款
-(void)gotoPayVC{
    NSString *globalStatus = self.model_BKMy_Order.is_global;
    NSString *order_no = self.model_BKMy_Order.order_no;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:globalStatus,@"globalStatus",order_no,@"orderNumber", nil];
    UIViewController *con = [[Mediator sharedInstance]BKOrder_paymentViewControllerWithParameter:dic];
    [self.navigationController pushViewController:con animated:YES];
}
#pragma mark ------查看物流;
-(void)gotoLogistics{
    BKMyOrderCheckLogisticsController *con = [BKMyOrderCheckLogisticsController new];
    con.orderNo = self.Order_no;
    
    [self.navigationController pushViewController:con animated:YES];
    
}
#pragma mark ------退换货
-(void)gotoReturngoods{
    BKMyOrderRetuanGoodDetailController *vc_BKMyOrderRetuanGoodDetail = [BKMyOrderRetuanGoodDetailController new];
    vc_BKMyOrderRetuanGoodDetail.orderModel = self.ordermodel;
   [ self.navigationController pushViewController:vc_BKMyOrderRetuanGoodDetail animated:YES];
    
}
#pragma mark -------拆单
-(void)gotoSplitOrder{
    BKMyOrderSplitController *con = [BKMyOrderSplitController new];
    con.model = self.model_BKMy_Order;
    
    [self.navigationController pushViewController:con animated:YES];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    NSArray *viewControllers = self.navigationController.viewControllers;
    if (viewControllers && viewControllers.count > 1) {
        UIViewController *vc = viewControllers[viewControllers.count - 1];
        if ([vc isKindOfClass:NSClassFromString(@"BKOrderPayForResultsViewController")]) {
            UIViewController *con = viewControllers[0];
            [self.navigationController setViewControllers:@[con] animated:YES];
      
            //[self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}
@end
